﻿using Syspetro.Core.SysInterface;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace Syspetro.DepRedis
{
    public class RedisLocker : ILock
    {
        readonly RedisHelper redis = new("ILock", 1);
        private static string Getkey(string key, bool threadsingle = true)
        {
            if (threadsingle) return key + Thread.CurrentThread.ManagedThreadId;
            else return key + "*";
        }

        public bool Get(string key)
        {
            var dbkey = redis.GetKeys(key + "*");
            if (dbkey.Count > 0)
                return false;
            else
                return true;
        }

        public async Task<bool> GetAwait(string key, TimeSpan? expiry = default)
        {
            double ms = expiry.Value.TotalMilliseconds;
            do
            {
                if (Get(key))
                    return true;
                await Task.Delay(100);
                ms -= 100;
            } while (ms > 0);
            return false;
        }
        public bool Expire(string key, TimeSpan? expiry = default)
        {
            var dbkeys = redis.GetKeys(key + "*");
            foreach (var dbkey in dbkeys)
                redis.KeyExpire(dbkey, expiry);
            return true;
        }
        public bool Remove(string key, bool threadsingle = true)
        {
            return redis.KeyDelete(Getkey(key, threadsingle));
        }

        public bool Set(string key, TimeSpan? expiry = default, bool threadsingle = true)
        {
            return redis.StringSet(Getkey(key, threadsingle), "ILock", expiry);
        }
    }
}
